﻿#include "MesQuerySettingPage.h"
#include <utils.h>

MesQuerySettingPage::MesQuerySettingPage(QWidget *parent)
	: SMTSettingPage(parent)
{
	ui = new Ui::MesQuerySettingPage();
	ui->setupUi(this);
	m_bFullPage = false;
}

MesQuerySettingPage::~MesQuerySettingPage()
{
	if (ui != nullptr)
	{
		delete ui;
	}
}

SMTString MesQuerySettingPage::name()
{
	const char *PageName = "MesQuerySettingPage";
	return SMTString(PageName);
}


void MesQuerySettingPage::initGUI()
{
	if (m_opr)
	{
		SMTVariableArray* inputParams;
		m_opr->GetInputVariables(&inputParams);

		SMTVariant tmpVariant;
		// 把数据从输入链表中取出放到界面上
		(*inputParams)[0].getValue(&tmpVariant);
		SMTString mesUrl;
		tmpVariant.toString(&mesUrl);
		ui->txtQueryUrl->setText(mesUrl.toLocal8Bit().constData());
		(*inputParams)[1].getValue(&tmpVariant);
		int tableNum;
		tmpVariant.toInt(&tableNum);
		ui->txtTableNum->setText(QString::number(tableNum));

		// 输入链表中第2个位置对应的元素为条码信息,将该元素与全局变量链表中同名的变量进行绑定
		bindGlobalVariable(m_availableRef, m_opr, 2, SMTRefFormat::SToS());
	}
}

void MesQuerySettingPage::updateGUI()
{
}

void MesQuerySettingPage::on_txtQueryUrl_textChanged(const QString& text)
{
	// 获取算子的输入变量链表
	SMTVariableArray* inputParams;
	m_opr->GetInputVariables(&inputParams);
	// 第0个位置放置的元素为MesQueryUrl
	(*inputParams)[0].setValue(text.toLocal8Bit().constData());
}

void MesQuerySettingPage::on_txtTableNum_textChanged(const QString& text)
{
	// 获取算子的输入变量链表
	SMTVariableArray* inputParams;
	m_opr->GetInputVariables(&inputParams);
	
	// 第1个位置放置的元素为TableNum
	int tableNum = text.trimmed().toInt();
	(*inputParams)[1].setValue(tableNum);
}

/**
* 将输入链表中 inputParaIdx 位置的元素 和 全局变量链表中的同名变量 进行绑定
* @availableArray   全局变量链表
* @opr              算子对象指针
* @inputParaIdx     输入链表中元素的索引
* @refFormat        绑定对象的类型转换
*/
void bindGlobalVariable(SMTVariableArray& availableArray, SMTOperator* opr, int inputParaIdx, SMTRefFormat refFormat)
{
	SMTVariableArray* pInputArray;
	opr->GetInputVariables(&pInputArray);
	if (pInputArray->length() < inputParaIdx)
	{
		return;
	}

	SMTVariable inputVariable = (*pInputArray)[inputParaIdx];
	int length = availableArray.length();
	SMTVariable variable;
	for (int x = 0; x < length; x++)
	{
		availableArray.select(x, &variable);
		if (!variable.valid() || !variable.enabled() || !variable.isInUse())
		{
			continue;
		}
		SMTOperator* oprParent = variable.parent();
		if (oprParent == nullptr)
		{
			if (variable.name() == inputVariable.name().toLocal8Bit().constData())
			{
				(*pInputArray)[inputParaIdx].clearReference();
				bool bRet = (*pInputArray)[inputParaIdx].addReference(variable, refFormat);
				(*pInputArray)[inputParaIdx].setUseReference(true);
				return;
			}
		}
	}
}
